<script>
  import { createSign } from "@al/h5sign";
  import H5ocr from "@al/h5ocr";

  let text = "";
  let show = false;
  const handleClick = () => {
    show = true;
    setTimeout(() => {
      if (document.getElementById("h5ocrRef")) {
        // 初始化ocr
        new H5ocr({
          element: document.getElementById("h5ocrRef"),
          className: "bnc-ocr",
          languageId: "zh",
          rotate: true,
          crop: true,
          compress: true,
          action: {
            uploadURL: "/api/upload",
          },
          transformUploadRequest(formData, headers) {
            return {
              formData,
              headers: {
                ...headers,
                sign: createSign(formData, {
                  type: "oao",
                }),
              },
            };
          },
          onSuccess: ({ previewBase, uploadBase }, res) => {
            console.log("拍照成功");
            if (res.success) {
              text = res.data || "";
            }
            show = false;
            // 拿到 data 图片数据 { file: File 文件, uploadBase: 上传图片base, previewBase: 预览图片base }
          },
          onFail: () => {
            console.log("拍照失败");
            show = false;
          },
          onClose: (type) => {
            console.log("onClose");
            console.log(type);
            show = false;
          },
        });
      }
    });
  };
</script>

<main>
  <div class="container">
    <span class="ocr" on:click={handleClick} on:keypress={handleClick}
      >开始OCR</span
    >
    <div class="content">
      识别结果：{text}
    </div>
    {#if show}
      <div class="h5ocr-container" id="h5ocrRef" />
    {/if}
  </div>
</main>

<style>
  .container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    padding: 0.24rem;
  }
  .content {
    flex: 1;
    font-size: 16px;
  }
  .h5ocr-container {
    overflow: hidden;
    touch-action: none;
    user-select: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 6;
    background: #fff;
    touch-action: none;
    user-select: none;
    font-family: "Poppins";
  }
  .ocr {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 6.56rem;
    height: 0.88rem;
    margin: 0.24rem 0;
    background: #fed000;
    font-size: 0.32rem;
    font-family: Roboto-Medium, Roboto;
    font-weight: 500;
    color: #131313;
  }
</style>
